package me.sunpeng.channel;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author sp
 */
public class DategramChannelDemo {

    /**
     * 发送
     */
    @Test
    public void sendDatagram() throws IOException {
        //打开Datagramchannel
        DatagramChannel sendChannel = DatagramChannel.open();
        InetSocketAddress sendAddress =
                new InetSocketAddress("127.0.0.1", 9999);

        //发送
        while (true) {
            ByteBuffer buffer = ByteBuffer.wrap("hello".getBytes(StandardCharsets.UTF_8));
            sendChannel.send(buffer, sendAddress);
            System.out.println("已经完成发送");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }


    /**
     * 接受的实现
     */
    @Test
    public void receiveDatagram() throws IOException {
        //打开DatagramChannel
        DatagramChannel receiveChannel = DatagramChannel.open();
        InetSocketAddress receiveAddres =
                new InetSocketAddress(9999);

        //绑定
        receiveChannel.bind(receiveAddres);

        //buffer
        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);

        // 接受
        while (true) {
            receiveBuffer.clear();
            SocketAddress socketAddress = receiveChannel.receive(receiveBuffer);
            receiveBuffer.flip();
            System.out.println(socketAddress.toString());
            System.out.println(StandardCharsets.UTF_8.decode(receiveBuffer));

        }


    }

    //连接 read 和 write
    @Test
    public void testConnect() throws IOException {
        //打开DatagramChannel
        DatagramChannel connChannel = DatagramChannel.open();

        // 绑定
        connChannel.bind(new InetSocketAddress(9999));

        //连接
        connChannel.connect(new InetSocketAddress("127.0.0.1", 9999));

        //write方法
        connChannel.write(ByteBuffer.wrap("hello".getBytes(StandardCharsets.UTF_8)));

        //read方法
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);

        while (true) {
            try {
                readBuffer.clear();
                connChannel.read(readBuffer);
                readBuffer.flip();
                System.out.println("receive: "+StandardCharsets.UTF_8.decode(readBuffer));
            } catch (Exception e) {
            }


        }
    }
}